package com.smartum.mpr.business;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartum.mpr.dao.TokenDao;
import com.smartum.mpr.dao.UserDao;
import com.smartum.mpr.exception.AlreadyExistsUserException;
import com.smartum.mpr.exception.AuthorizationException;
import com.smartum.mpr.exception.DatabaseIntegrityException;
import com.smartum.mpr.exception.NotExistsTokenException;
import com.smartum.mpr.exception.NotExistsUserException;
import com.smartum.mpr.model.Token;
import com.smartum.mpr.model.User;
import com.smartum.mpr.util.SecurityUtil;

@Service
public class UserBusiness extends BaseBusiness {

	@Autowired
	private UserDao userDao;
	@Autowired
	private TokenDao tokenDao;

	public User getById(long id){
		return userDao.get(id);
	}

	public void registerUser(User user) throws AlreadyExistsUserException {
		userDao.searchRegistrationUserLoginAndEmail(user.getUsername(), user.getEmail());
		userDao.save(user);
	}

	public User getUserByUsernameAndPassword(String username, String password) throws DatabaseIntegrityException,
	        AuthorizationException {
		return userDao.findUserByLoginAndPassword(username, password);
	}

	public User getUserByToken(String token) throws DatabaseIntegrityException, AuthorizationException,
	        NotExistsTokenException {
		return userDao.findUserByToken(token);
	}


	public void remindPassword(String email) {

	}

	public void addFlagToUser(Long userId) throws NotExistsUserException{
		User user = userDao.get(userId);
		if(user==null){
			throw new NotExistsUserException();
		}
	}

	public String authoriseUser(String username, String password) throws DatabaseIntegrityException,
	        AuthorizationException {
		User user = userDao.findUserByLoginAndPassword(username, password);
		Token token = new Token();

		String tokenText = username + System.currentTimeMillis();
		tokenText = SecurityUtil.stringToMD5(tokenText);
		token.setToken(tokenText);
		token.setUser(user);
		tokenDao.save(token);

		return tokenText;
	}

}
